use tokio::time;

use crate::{components, dao};
use crate::models::models::components::v2ray::info::ComponentV2rayState;
use crate::models::models::components::v2ray::router::ComponentV2rayRouter;
use crate::runtime::response::MagicBoxResponse;
use crate::runtime::result::MagicBoxResult;

#[tauri::command(rename_all = "snake_case")]
pub(crate) async fn invoke_component_v2ray_add_router(router: ComponentV2rayRouter, restart: bool) -> MagicBoxResult<MagicBoxResponse<()>> {
    dao::components::v2ray::router::add_router(router.clone())?;

    // 重启服务
    if restart && ComponentV2rayState::Running == components::v2ray::manager::manager().state()? {
        components::v2ray::manager::manager().stop()?;

        time::sleep(time::Duration::from_millis(1000)).await;
        components::v2ray::manager::manager().start()?;
    }

    Ok(MagicBoxResponse::new_empty_success())
}